package com.joymart.recipient.controller;

import com.joymart.common.utils.SecurityUtils;
import com.joymart.recipient.model.Recipient;
import com.joymart.recipient.service.RecipientService;
import com.joymart.common.error.handling.JoymartBusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
public class RecipientController {

    @Autowired
    private RecipientService recipientService;

    @GetMapping("/recipients")
    public List<Recipient> getAll() {
        String currentUserId = SecurityUtils.getCurrentUserId();
        return recipientService.findRecipientsByUserId(currentUserId);
    }

    @GetMapping("/recipients/{id}")
    public Recipient getById(@PathVariable String id) {
        String currentUserId = SecurityUtils.getCurrentUserId();
        Recipient recipient = recipientService.findById(id);

        // 检验是否是当前用户的数据
        if (!recipient.getUserId().equals(currentUserId)) {
            throw new JoymartBusinessException("您没有权限查看此数据");
        }

        return recipient;
    }

    @PostMapping("/recipients")
    public Recipient create(@RequestBody Recipient recipient) {

        return recipientService.create(recipient);
    }

    @PutMapping("/recipients/{id}")
    public Recipient update(@PathVariable String id, @RequestBody Recipient recipient) {
        // 确保更新的Recipient的ID匹配
        recipient.setId(id);
        String currentUserId = SecurityUtils.getCurrentUserId();

        // 检查要更新的Recipient是否属于当前用户
        Recipient existingRecipient = recipientService.findById(id);
        if (!existingRecipient.getUserId().equals(currentUserId)) {
            throw new JoymartBusinessException("您没有权限更新此数据");
        }

        recipient.setUserId(currentUserId);  // 确保用户ID正确
        recipient.setCreatedAt(existingRecipient.getCreatedAt());
        return recipientService.update(recipient);
    }

    @DeleteMapping("/recipients/{id}")
    public void delete(@PathVariable String id) {
        String currentUserId = SecurityUtils.getCurrentUserId();

        // 检查要删除的Recipient是否属于当前用户
        Recipient existingRecipient = recipientService.findById(id);
        if (!existingRecipient.getUserId().equals(currentUserId)) {
            throw new JoymartBusinessException("您没有权限删除此数据");
        }

        recipientService.delete(id);
    }
}